package portal.bean;

import java.lang.reflect.Field;

import java.util.List;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import javax.servlet.http.HttpServletRequest;

import oracle.adf.rc.catalog.Folder;
import oracle.adf.view.rich.component.rich.nav.RichBreadCrumbs;
import oracle.adf.view.rich.component.rich.nav.RichCommandLink;

import oracle.adfinternal.rc.catalog.lite.ImmutableUrlElement;
import oracle.adfinternal.rc.jndi.CatalogContextWrapper;

import oracle.webcenter.framework.view.JSFUtils;
import oracle.webcenter.navigationframework.NavigationContext;
import oracle.webcenter.navigationframework.NavigationModel;
import oracle.webcenter.navigationframework.NavigationResource;
import oracle.webcenter.navigationframework.ResourceNotFoundException;
import oracle.webcenter.portalframework.sitestructure.SiteStructure;
import oracle.webcenter.portalframework.sitestructure.SiteStructureContext;
import oracle.webcenter.portalframework.sitestructure.SiteStructureResource;
import oracle.webcenter.portalframework.sitestructure.handler.CustomViewHandler;


public class NavigationBean {
    private String topnodepath = "";
    private String tempparam;
    private static final String JSF_ACCESSOR_NAME = "navigationBean";
    private RichBreadCrumbs webBreadCrumbs;


    public static NavigationBean getCurrentInstance() {
        Map<String, Object> session =
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        NavigationBean navigationBean =
            (NavigationBean)session.get(JSF_ACCESSOR_NAME);

        if (navigationBean == null) {
            navigationBean = new NavigationBean();
            session.put(JSF_ACCESSOR_NAME, navigationBean);
        }

        return navigationBean;
    }

    public NavigationBean() {
        super();
    }

    public String pprnav() {

        return null;
    }

    private void findcurrentnode() {
        UIComponent uicmp = webBreadCrumbs.getNodeStamp();
        System.out.println("");
        //        String elstring ="#{breadCrumbsItem}";
        //        SiteStructureResource node = (SiteStructureResource)JSFUtils.resolveExpression(elstring);
        //        SiteStructureResource tempnode = node;
        //        SiteStructureResource topnode = tempnode;
        //        while (tempnode.isNavigable() && tempnode.getParent() != null) {
        //            topnode = tempnode;
        //            tempnode = tempnode.getParent();
        //
        //        }
        //        if(topnode.getPath()!=null)
        //            topnodepath = topnode.getPath();
        //        if (topnodepath.equals("")) {
        //            try {
        //                Field f = topnode.getClass().getDeclaredField("mResource");
        //                f.setAccessible(true);
        //                CatalogContextWrapper recwrap =
        //                    (CatalogContextWrapper)f.get(topnode);
        //                ImmutableUrlElement imurl = (ImmutableUrlElement)recwrap.getCatalogFolder();
        //                topnodepath =imurl.getUrl();
        //                topnodepath = topnodepath.substring(1, topnodepath.length());
        //
        //            } catch (NoSuchFieldException e) {
        //                e.printStackTrace();
        //            } catch (IllegalAccessException e) {
        //                e.printStackTrace();
        //            }
        //        }
    }

    public void processAction(ActionEvent actionEvent) {
        topnodepath = "";
        FacesContext fctx = FacesContext.getCurrentInstance();
        //System.out.println(fctx.getViewRoot().getViewId());
        SiteStructureResource node =
            (SiteStructureResource)actionEvent.getComponent().getAttributes().get("node");
        String path =
            (String)actionEvent.getComponent().getAttributes().get("path");
        //        SiteStructureResource tempnode = node;
        //        SiteStructureResource topnode = tempnode;
        //        while (tempnode.isNavigable() && tempnode.getParent() != null) {
        //            topnode = tempnode;
        //            tempnode = tempnode.getParent();
        //
        //        }
        //        if (topnode.getPath() != null)
        //            topnodepath = topnode.getPath();
        //        if (topnodepath.equals("")) {
        //            try {
        //                Field f = topnode.getClass().getDeclaredField("mResource");
        //                f.setAccessible(true);
        //                CatalogContextWrapper recwrap =
        //                    (CatalogContextWrapper)f.get(topnode);
        //                ImmutableUrlElement imurl =
        //                    (ImmutableUrlElement)recwrap.getCatalogFolder();
        //                topnodepath = imurl.getUrl();
        //                topnodepath = topnodepath.substring(1, topnodepath.length());
        //
        //            } catch (NoSuchFieldException e) {
        //                e.printStackTrace();
        //            } catch (IllegalAccessException e) {
        //                e.printStackTrace();
        //            }
        //        }
        //        if (node == null && path == null)
        //            return;
        CustomViewHandler.redirectPrettyUrlIfNeeded(node);

    }


    public void setTopnodepath(String topnodepath) {
        this.topnodepath = topnodepath;
    }

    public String getTopnodepath() {
        if (topnodepath.equals("")) {
            HttpServletRequest request =
                (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            String struri = request.getRequestURI();
            struri =
                    struri.substring(struri.indexOf("/faces/") + 7, struri.length());
            //System.out.println(struri);
            String elexp = "#{navigationContext.defaultNavigationModel}";
            SiteStructure str =
                (SiteStructure)JSFUtils.resolveExpression(elexp);
            List<NavigationResource> lstnavresources;

            NavigationResource tempnode=null;
            try {
                tempnode = str.getResource(struri);
            } catch (ResourceNotFoundException e) {
                //e.printStackTrace();
            }
            if(tempnode!=null)
            {
                NavigationResource topnode = tempnode;
                while (tempnode.isNavigable() &&
                       tempnode.getParent() != null) {
                    topnode = tempnode;
                    tempnode = tempnode.getParent();
                }
                if (topnode.getPath() != null)
                    topnodepath = topnode.getPath();
                else {
                    Field f;
                    try {
                        f = topnode.getClass().getDeclaredField("mResource");
                        f.setAccessible(true);
                        CatalogContextWrapper recwrap =
                            (CatalogContextWrapper)f.get(topnode);
                        Folder fld = recwrap.getCatalogFolder();
                        ImmutableUrlElement imurl = (ImmutableUrlElement)fld;
                        topnodepath = imurl.getUrl();
                        topnodepath =
                                topnodepath.substring(1, topnodepath.length());
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    

                }
            }
          
        }
        return topnodepath;
    }
    public void menuItemClick(ActionEvent actionEvent) {
        // Add event code here...
        RichCommandLink comp = (RichCommandLink)actionEvent.getComponent();
        NavigationResource node =(NavigationResource) comp.getAttributes().get("node");
        String strEL =null;                          
        NavigationContext navContext = SiteStructureContext.getInstance();
        NavigationModel navmd;
        try {
            //lay Navigation mac dinh cua he thong
            navmd = navContext.getDefaultNavigationModel();
          
            //lay cac node con của node duoc click
            List<NavigationResource> lsnode = node.getChildren();
            int i = lsnode.size();
            //dieu huong den node(trang) dau tien cua nhanh
            if (i > 0) {
                NavigationResource nodechidle = lsnode.get(0);
                String nodeID = nodechidle.getPrettyUrl().substring(nodechidle.getPrettyUrl().indexOf("/")+1,nodechidle.getPrettyUrl().length());
                strEL ="#{navigationContext.defaultNavigationModel.node['" + nodechidle.getPrettyUrl() + "']}";
                SiteStructureResource sStrResource = (SiteStructureResource)JSFUtils.resolveExpression(strEL);
                CustomViewHandler.redirectPrettyUrlIfNeeded(sStrResource);// Only run when parameter "oracle.webcenter.navigationframework.REDIRECT_OPTIONS" was set in web.xml
            }


        } catch (ResourceNotFoundException e) {
            e.printStackTrace();
        }
    }
    public void setTempparam(String tempparam) {
        this.tempparam = tempparam;
    }

    public String getTempparam() {
        findcurrentnode();
        return tempparam;
    }

    public void setWebBreadCrumbs(RichBreadCrumbs webBreadCrumbs) {
        this.webBreadCrumbs = webBreadCrumbs;
    }

    public RichBreadCrumbs getWebBreadCrumbs() {
        return webBreadCrumbs;
    }
}
